//
//  OtherViewModel.swift
//  DaRings
//
//  Created by 易先生 on 2022/10/28.
//

import UIKit
import Differentiator
import RxSwift
import RxCocoa
import CRPSmartRing
import SwiftDate

enum OtherSectionItem {
    
    case unitFormatItem(cellModel: OtherTimeFormatCellModel)
    case sedentaryReminderItem(cellModel: OtherSedentaryReminderCellModel)
    case lowBatteryReminderItem(cellModel: OtherSedentaryReminderCellModel)

    case heartRateWarningItem(cellModel: OtherSedentaryReminderCellModel)
    case maximumHeartRateItem(cellModel: OtherTimeFormatCellModel)

}

struct OtherSectionModel {
    var header: String
    var items: [OtherSectionItem]
}

extension OtherSectionModel: SectionModelType {

    init(original: OtherSectionModel, items: [OtherSectionItem]) {
        self = original
        self.items = items
    }
}



class OtherViewModel: NSObject {

    public let sections = BehaviorRelay<[OtherSectionModel]>(value: [])
    
    private var profile = UserCacheManagement.userInfo()

    override init() {
        super.init()
        getSectionItems()
    }
    
    public func getSectionItems() {

        var otherSections: [OtherSectionModel] = []
        otherSections.append(getOtherSectionModel())
        
        otherSections.append(getHeartRateWarningSectionModel())

        sections.accept(otherSections)
    }

}

extension OtherViewModel{
    
    private func getOtherSectionModel() -> OtherSectionModel {
                
        var otherCells: [OtherSectionItem] = []
        
        let untilFormatCellModel = OtherTimeFormatCellModel(title: "measurement_system".language)
        untilFormatCellModel.value.accept(profile.unitType.localeName)
        otherCells.append(.unitFormatItem(cellModel: untilFormatCellModel))
        
        var isEnabled = true
        if BluetoothManager.shared.bluetoothState == .poweredOff || BluetoothManager.shared.deviceState != .connected {
            isEnabled = false
        }
        let sitRemind = UserCacheManagement.userInfo().sitRemind
        let sedentaryReminderCellModel = OtherSedentaryReminderCellModel(title: "other_settings_eminders_to_move".language,
                                                                         content: "other_settings_eminders_to_move_hint".language,
                                                                         isOn: sitRemind,isEnabled: isEnabled)
        otherCells.append(.sedentaryReminderItem(cellModel: sedentaryReminderCellModel))

        sedentaryReminderCellModel.isOpen.subscribe(onNext: { [weak self] isOn in
            guard let self = self else { return }
            self.setSitRemind(isOn: isOn)
            var userModel = UserCacheManagement.userInfo()
            userModel.sitRemind = isOn
            UserCacheManagement.updateUserInfo(userModel)
        }).disposed(by: rx.disposeBag)
        
        let lowBatteryReminder = UserCacheManagement.userInfo().lowBatteryReminder
        let lowBatteryReminderCellModel = OtherSedentaryReminderCellModel(title: "other_low_battery_reminder_title".language,
                                                                         content: "other_low_battery_reminder_hit".language,isOn: lowBatteryReminder)
        otherCells.append(.lowBatteryReminderItem(cellModel: lowBatteryReminderCellModel))
        lowBatteryReminderCellModel.isOpen.subscribe(onNext: { isOn in
            var userModel = UserCacheManagement.userInfo()
            userModel.lowBatteryReminder = isOn
            UserCacheManagement.updateUserInfo(userModel)
        }).disposed(by: rx.disposeBag)

        
        let section = OtherSectionModel(header: "",items: otherCells)
        return section
    }

    private func setWatchUntil() {
        
    }
    
    private func setSitRemind(isOn:Bool) {
        
        /// 久坐提醒 1小时 没有 50步 提醒
        let model = CRPActivityReminderModel(open: isOn, period: 60, steps: 50, startHour: 10, endHour: 22)
        BluetoothManager.shared.setActivityReminder(model)
        
    }
    
}


extension OtherViewModel{
    
    /// 心率预警
    /// - Returns: OtherSectionModel
    private func getHeartRateWarningSectionModel() -> OtherSectionModel {

        var cells: [OtherSectionItem] = []

        let maxHRContent = "device_heart_rate_remind_message".language(with: ["\(profile.defaultMaxHR)"])
        let heartRemind = UserCacheManagement.userInfo().heartRemind

        var isEnabled = true
        if BluetoothManager.shared.bluetoothState == .poweredOff || BluetoothManager.shared.deviceState != .connected {
            print(BluetoothManager.shared.bluetoothState.rawValue)
            print(BluetoothManager.shared.deviceState.rawValue)
            isEnabled = false
        }
        let heartRateWarningSwitchCellModel = OtherSedentaryReminderCellModel(
            title: "device_heart_rate_remind_title".language,
            content: maxHRContent,
            isOn: heartRemind,
            isEnabled: isEnabled)
        heartRateWarningSwitchCellModel.isOpen.subscribe(onNext: { [weak self] isOn in
            guard let self = self else { return }
            var userModel = UserCacheManagement.userInfo()
            userModel.heartRemind = isOn
            UserCacheManagement.updateUserInfo(userModel)
            self.sendHeartRateRemind(isRemind: isOn, max: userModel.warningMxHR)
            self.getSectionItems()
        }).disposed(by: rx.disposeBag)
        cells.append(.heartRateWarningItem(cellModel: heartRateWarningSwitchCellModel))
        
        if heartRemind {
            let maximumHeartRateCellModel = OtherTimeFormatCellModel(title: "device_heart_rate_remind_max".language)
            maximumHeartRateCellModel.value.accept(profile.getMaxHR())
            cells.append(.maximumHeartRateItem(cellModel: maximumHeartRateCellModel))
        }
        
        let section = OtherSectionModel(header: "",items: cells)
        return section
    }
    
    
    public func sendHeartRateRemind(isRemind: Bool, max: Int) {
        let model = CRPHRRemind(isRemind: isRemind, max: max)
        BluetoothManager.shared.sendHeartRateRemind(model)
    }
}
